<template>
  <div class="app-container">
    <!-- 站点选择 -->
    <el-card class="site-list-container" body-style="padding-left: 10px; padding-right: 10px">
      <div class="site-list-wrapper">
        <el-input class="site-search" v-model="keywords" size="small" placeholder="请输入关键字查询" clearable>
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <div class="site-list">
          <template v-for="(item, index) in siteList">
            <div v-if="item.siteName.indexOf(keywords) !== -1" class="site-btn"
              :class="{ selected: curSiteId === item.id }" size="small" :key="index"
              @click="curSiteId = curSiteId === item.id ? '' : item.id">
              {{ item.siteName }}
            </div>
          </template>
        </div>
      </div>
    </el-card>

    <!-- 设备table -->
    <el-card class="station-table-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="充电桩名称" prop="stationName">
          <el-input v-model="queryParams.stationName" placeholder="请输入充电桩名称" clearable style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="设备状态" prop="orderStatus">
          <el-select v-model="queryParams.deviceStatus" style="width: 240px" clearable>
            <el-option label="正常" value="NORMAL">正常</el-option>
            <el-option label="故障" value="BREAK">故障</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="在线状态" prop="onlineStatus">
          <el-select v-model="queryParams.onlineStatus" style="width: 240px" clearable>
            <el-option label="正常" value="ONLINE">正常</el-option>
            <el-option label="离线" value="OFFLINE">离线</el-option>
            <el-option label="未注册" value="UNREGISTER">未注册</el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-download" size="mini" @click="exportData">导出</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="editVisible = true">新增</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="tableList">
        <el-table-column label="充电桩名称" prop="stationName" width="150" />
        <el-table-column label="设备id" prop="id" width="180" />
        <el-table-column label="站点id" prop="siteId" width="180" />
        <el-table-column label="设备类型" prop="deviceType" width="150" />
        <el-table-column label="序列号" prop="deviceSerialNum" width="150" />
        <el-table-column label="设备状态" prop="deviceStatus" width="100">
          <template slot-scope="scope">
            <span>{{ deviceStatusMap[scope.row.deviceStatus] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="在线状态" prop="onlineStatus" width="100">
          <template slot-scope="scope">
            <span>{{ onlineStatusMap[scope.row.onlineStatus] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="到期时间" prop="expireTime" width="160" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
          <template slot-scope="scope" v-if="scope.row.roleId !== 1">
            <el-button size="mini" type="text" icon="el-icon-search" @click="toDetail(scope.row)">详情</el-button>
            <el-button size="mini" type="text" icon="el-icon-search" @click="showQrcode(scope.row)">二维码</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['system:role:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" :page-sizes="[10, 20, 30, 50, 500, 1000]" />
    </el-card>

    <!-- 新增设备 -->
    <EditModal title="新增设备" :data="stationData" :siteList="siteList" :visible="editVisible" @success="onEditSuccess"
      @cancel="onEditCancel"></EditModal>

    <el-dialog title="二维码" :visible.sync="qrcodeVisible" width="1000px" append-to-body :close-on-click-modal="false">
      <div class="qrcode-container" id="qrcode-container">
        <div class="qrcode-entry">
          <div class="qrcode-entry__title">主机二维码</div>
          <canvas id="port-main"></canvas>
          <div class="qrcode-entry__num">{{ curDeviceSerialNum }}</div>
          <el-button v-show="donwloadVisible" class="qrcode-entry__download" size="small" type="primary"
            @click="htmlToImage">下载</el-button>
        </div>
        <div class="qrcode-wrapper">
          <div class="qrcode-port" v-for="i in 10">
            <div class="qrcode-port__title">通道{{ i }}:</div>
            <canvas class="qrcode-port__canvas" :id="'port' + i"></canvas>
            <div class="qrcode-port__num">{{ curDeviceSerialNum }}</div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import EditModal from "./components/EditModal";
import { getListAPI as getSiteListAPI } from "@/api/charge/site";
import { getListAPI, addOrUpdateAPI, deleteAPI } from "@/api/charge/station";
import QRCode from "qrcode";
import html2canvas from "html2canvas";
import { exportExcel, exportExcelFromAPI } from "@/utils/utils";

const generateUUID = () => {
  let d = new Date().getTime();
  if (window.performance && typeof window.performance.now === "function") {
    // use high-precision timer if available
    d += performance.now();
  }
  let uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
    /[xy]/g,
    function (c) {
      let r = (d + Math.random() * 16) % 16 | 0;
      d = Math.floor(d / 16);
      return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
    }
  );
  return uuid;
};
export default {
  name: "Station",
  dicts: ["sys_normal_disable"],
  components: { EditModal },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      tableList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      editVisible: false,
      // 是否显示弹出层（数据权限）
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      qrcodeVisible: false,

      // 日期范围
      dateRange: [],

      deviceStatusMap: {
        NORMAL: "正常",
        BREAK: "故障",
      },
      onlineStatusMap: {
        ONLINE: "在线",
        OFFLINE: "离线",
        UNREGISTER: "未注册",
      },

      // 站点搜索关键词
      keywords: "",
      curSiteId: "",

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationName: "",
      },
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        siteId: [{ required: true, message: "请输入站点id", trigger: "blur" }],
        stationName: [
          { required: true, message: "请输入设备名称", trigger: "blur" },
        ],
        deviceType: [
          { required: true, message: "请选择设备类型", trigger: "change" },
        ],
        deviceSerialNum: [
          { required: true, message: "请输入序列号", trigger: "blur" },
        ],
      },

      // 设备收费模式
      chargeForm: {},

      // 全部站点列表
      siteList: [],

      stationData: {},

      // 二维码
      curDeviceSerialNum: "",
      donwloadVisible: true,
    };
  },
  created() {
    this.getSiteList();
    this.getList();
  },
  watch: {
    curSiteId() {
      this.getList();
    },
  },
  methods: {
    exportData() {
      exportExcelFromAPI("/charge/station/list/export", {
        ...this.queryParams,
        pageNum: 1,
        pageSize: 10000,
      });
      return false;
      exportExcel({
        data: this.formatTableList(this.tableList),
        headers: [
          { label: "充电桩名称", key: "stationName" },
          { label: "设备id", key: "id" },
          { label: "站点id", key: "siteId" },
          { label: "设备类型", key: "deviceType" },
          { label: "序列号", key: "deviceSerialNum" },
          { label: "设备状态", key: "deviceStatus" },
          { label: "在线状态", key: "onlineStatus" },
          { label: "到期时间", key: "expireTime" },
          { label: "创建时间", key: "createTime" },
        ],
        filename: "设备数据.xlsx",
      })
    },
    // 格式化表格数据
    formatTableList(data) {
      return data.map(item => {
        return {
          ...item,
          deviceStatus: this.deviceStatusMap[item.deviceStatus],
          onlineStatus: this.onlineStatusMap[item.onlineStatus],
          expireTime: this.parseTime(item.expireTime),
          createTime: this.parseTime(item.createTime),
        }
      })
    },
    // 保存图片
    htmlToImage() {
      this.donwloadVisible = false;

      this.$nextTick(() => {
        html2canvas(document.querySelector(`#port-main`), {
          useCORS: true,
        }).then((canvas) => {
          const base64 = canvas.toDataURL("image/png");
          let a = document.createElement("a");
          a.href = base64;
          a.download = `${generateUUID()}.png`;
          a.click();
          this.donwloadVisible = true;
        });
      });
    },
    showQrcode(row) {
      this.qrcodeVisible = true;
      this.curDeviceSerialNum = row.deviceSerialNum;
      this.donwloadVisible = true;

      this.$nextTick(() => {
        // 主机二维码
        let canvas = document.getElementById(`port-main`);
        let codeUrl = `https://api-charge.znscxny.com/qrcode?stationSerialNumPort=${row.deviceSerialNum}`;
        console.log(codeUrl);

        QRCode.toCanvas(canvas, codeUrl, {
          width: 150,
          height: 150,
        });
        // 通道二维码
        for (let i = 1; i <= 10; i++) {
          let canvas = document.getElementById(`port${i}`);
          let codeUrl = `https://api-charge.znscxny.com/qrcode?stationSerialNumPort=${row.deviceSerialNum}&port=${i}`;
          console.log(codeUrl);

          QRCode.toCanvas(canvas, codeUrl, {
            width: 120,
            height: 120,
          });
        }
      });
    },
    // 编辑成功回调
    onEditSuccess() {
      this.editVisible = false;
      this.getList();
    },
    // 编辑关闭回调
    onEditCancel() {
      this.editVisible = false;
    },
    // 查询全部站点
    getSiteList() {
      getSiteListAPI({
        pageNum: "1",
        pageSize: "500",
      }).then((res) => {
        this.siteList = res.rows;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      getListAPI({
        ...this.queryParams,
        siteId: this.curSiteId,
      }).then((res) => {
        this.tableList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm("确认删除吗？")
        .then(function () {
          return deleteAPI([row.id]);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 跳转详情页 */
    toDetail(row) {
      this.$router.push({
        path: "station/edit",
        query: {
          siteId: row.siteId,
          stationName: row.stationName,
          id: row.id,
        },
      });
    },
  },
};
</script>
<style scoped lang="scss">
.app-container {
  height: 100%;
  display: flex;

  .site-list-container {
    width: 20%;
    flex: none;
    margin-right: 20px;

    .site-list-wrapper {
      position: relative;
      overflow: hidden;

      .site-search {
        position: absolute;
        top: 0;
        margin-bottom: 20px;
      }

      .site-list {
        margin-top: 40px;
        overflow: auto;

        .site-btn {
          width: 100%;
          font-size: 12px;
          color: #606266;
          padding: 9px 15px;
          text-align: left;
          border-radius: 2px;
          cursor: pointer;

          &:hover {
            color: #1890ff;
            background-color: #e8f4ff;
          }

          &.selected {
            color: #1890ff;
            background-color: #e8f4ff;
          }
        }
      }
    }
  }

  .station-list-container {
    width: 80%;
    flex: auto;
  }
}

.qrcode-container {
  display: flex;

  .qrcode-entry {
    display: flex;
    flex-direction: column;
    text-align: center;
    margin-right: 20px;

    .qrcode-entry__download {
      width: 100px;
      margin: 10px auto 0;
    }
  }

  .qrcode-wrapper {
    flex: auto;
    display: flex;
    flex-wrap: wrap;

    .qrcode-port {
      width: 20%;
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 20px;

      .qrcode-port__title {}

      .qrcode-port__canvas {
        width: 100px;
        height: 100px;
      }

      .qrcode-port__num {
        font-size: 13px;
      }
    }
  }
}
</style>
